import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { getArticleDetailByIdAction } from '@/store/action/article';
import { useParams } from 'react-router-dom';
import { useAppSelector } from '@/store';
import { sanitize } from 'dompurify';
import dayjs from 'dayjs';
import Skeleton from '@/components/Skeleton';
import hljs from 'highlight.js';
import classnames from 'classnames';

import 'highlight.js/styles/vs2015.css';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import { clearCommentsAction, getCommentsByIdAction } from '@/store/action/comment';
import CommentFooter from './components/CommentFooter';
import CommentReply from './components/CommentReply';
import { Popup } from 'antd-mobile';

export default function Article() {
  const dispatch = useDispatch();
  const { id } = useParams<{ id: string }>();
  const { detail } = useAppSelector((state) => state.article);
  const { comments, originComment } = useAppSelector((state) => state.comment);
  const { results: commentList } = comments;

  const [navAuthShow, setNavAuthShow] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const authRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    dispatch(getArticleDetailByIdAction(id));
  }, [id, dispatch]);

  useEffect(() => {
    if (!detail.art_id) {
      return;
    }
    hljs.configure({
      ignoreUnescapedHTML: true,
    });
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length) {
      return codes.forEach((item) => {
        hljs.highlightElement(item as any);
      });
    }
    const preCodes = document.querySelectorAll('.dg-html pre');
    if (preCodes.length) {
      return preCodes.forEach((item) => {
        hljs.highlightElement(item as any);
      });
    }
  }, [detail.art_id]);

  const scrollFn = () => {
    const top = authRef.current!.getBoundingClientRect().top;
    if (top < 10) {
      setNavAuthShow(true);
    } else {
      setNavAuthShow(false);
    }
  };

  useEffect(() => {
    if (!detail.art_id) return;

    wrapRef.current?.addEventListener('scroll', scrollFn);
  }, [detail.art_id]);

  useEffect(() => {
    const wrapDOM = wrapRef.current!;
    return () => {
      if (!detail.art_id) return;
      dispatch(clearCommentsAction());
      dispatch({ type: 'article/saveDetail', payload: {} });
      wrapDOM.removeEventListener('scroll', scrollFn);
    };
  }, [dispatch, detail.art_id]);

  useEffect(() => {
    dispatch(getCommentsByIdAction({ type: 'a', source: id }));
  }, [id, dispatch]);

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar right={<Icon type="icongengduo" />}>
          {navAuthShow && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span className={classnames('follow', detail.is_followed ? 'followed' : '')}>
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {!detail.art_id ? (
          <Skeleton></Skeleton>
        ) : (
          <div className="wrapper" ref={wrapRef}>
            <div className="article-wrapper">
              <div className="header">
                <h1 className="title" id="title">
                  {detail.title}
                </h1>

                <div className="info">
                  <span>{dayjs(detail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span className="follow">{detail.is_followed ? '已关注' : '关注'}</span>
                </div>
              </div>

              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: sanitize(detail.content),
                  }}
                ></div>
                <div className="date">发布文章时间：{dayjs().from(detail.pubdate)}</div>
                {/* 💥 静态结构和date 同级 */}
                <div className="divider"></div>
                <div className="comment">
                  {/* 评论总览信息 */}
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {/* 评论列表 */}
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {commentList.map((item) => {
                        return <CommentItem comment={item} key={item.com_id} />;
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
        <CommentFooter></CommentFooter>
        <Popup visible={!!originComment.com_id} position="right">
          <CommentReply></CommentReply>
        </Popup>
      </div>
    </div>
  );
}
